package com.cennavi.minemap.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientUtil {
    public static CloseableHttpClient httpclient = HttpClients.createDefault();

    public static String doGet(String url) throws ClientProtocolException, IOException {
        //url = URLEncoder.encode(url,"utf-8");
        String body = "{UTF-8}";
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();

        body = EntityUtils.toString(entity, "utf-8");
        return body;
    }

    public static String doPost(String url, JSONObject json) {
        return doPost(url, json.toJSONString());
    }

    public static String doPost(String url, String json) {
        try {
            String body;
            HttpPost httpPost = new HttpPost(url);

            JSONObject jsonParam = JSONObject.parseObject(json);
            StringEntity stringEntity = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);

            HttpResponse response = httpclient.execute(httpPost);

            HttpEntity entity = response.getEntity();

            body = EntityUtils.toString(entity, "utf-8");
            return body;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
